package com.lepu.app.fun.bbs.adapter;

import java.sql.Date;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.InputFilter;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.app.utils.LoginUtil;
import com.app.utils.Setting;
import com.core.lib.application.BaseFragmentActivity;
import com.core.lib.core.ApiClient;
import com.core.lib.core.AsyncRequest;
import com.core.lib.utils.EmojiFilter;
import com.core.lib.utils.PopUtil;
import com.core.lib.utils.main.DateUtilBase;
import com.core.lib.utils.main.UIHelper;
import com.core.lib.widget.CircularImageView;
import com.lepu.app.fun.bbs.BbsDetailActivity;
import com.lepu.app.fun.bbs.bean.BeanBbsDetail;
import com.lepu.app.fun.my.MyReportActivity;
import com.lepu.pasm.R;

public class AdapterBbsDetail extends BaseAdapter implements AsyncRequest{

	private LayoutInflater mLayoutInflater = null;
	private Context mContext = null;
	private ArrayList<BeanBbsDetail> mArrayList = null;
	private String mThreadId = null;
	private BeanBbsDetail mBeanBbsDetail = null; //记录当前选中的item
	private TextView mFavorTextView = null; //记录点赞view
	private TextView mFavorCountTextView = null; //记录点赞次数view
	
	private String REQUEST_FAVOR = "request_favor";
	private String REQUEST_FAVOR_EXIT = "request_favor_exit";
	private String REQUEST_REPLY = "request_reply";
	private static final int MSG_FAVOR_SUCESS = 11;
	private static final int MSG_FAVOR_FAIL = 12;
	private static final int MSG_FAVOR_EXIT_SUCESS = 13;
	private static final int MSG_FAVOR_EXIT_FAIL = 14;
	private static final int MSG_REPLY_SUCESS = 15;
	private static final int MSG_REPLY_FAIL = 16;

	public AdapterBbsDetail(Context context,ArrayList<BeanBbsDetail> arrayList, String threadId) {
		mContext = context;
		mLayoutInflater = LayoutInflater.from(context);
		mArrayList = arrayList;
		mThreadId = threadId;
	}

	@Override
	public int getCount() {
		int size = 0;
		if (mArrayList != null && mArrayList.size() > 0) {
			size = mArrayList.size();
		}
		return size;
	}

	@Override
	public Object getItem(int position) {
		return position;
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@SuppressLint("InflateParams")
	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {

		final ViewHolder holder;

		if (convertView == null) {
			convertView = mLayoutInflater.inflate(R.layout.bbs_detail_list_item, null);

			holder = new ViewHolder();

			LinearLayout itemLayout = (LinearLayout) convertView.findViewById(R.id.mainItemLayout);
			CircularImageView accountIconImageView = (CircularImageView) convertView.findViewById(R.id.iconImageView);
			TextView nameTextView = (TextView) convertView.findViewById(R.id.titleTextView);
			TextView timeTextView = (TextView) convertView.findViewById(R.id.timeTextView);
			TextView storyTextView = (TextView) convertView.findViewById(R.id.storyTextView);
			TextView contentTextView = (TextView) convertView.findViewById(R.id.bottomTitleTextView);
			TextView praiseCountTextView = (TextView) convertView.findViewById(R.id.bbs_comment_praise_count);
			TextView praiseIconTextView = (TextView) convertView.findViewById(R.id.bbs_comment_praise_text);
			TextView replyIconTextView = (TextView) convertView.findViewById(R.id.bbs_comment_reply_text);
			
			LinearLayout replayLayout = (LinearLayout) convertView.findViewById(R.id.replayLayout);
			TextView replyNameTextView = (TextView) convertView.findViewById(R.id.replyNameTextView);
			TextView replyContentTextView = (TextView) convertView.findViewById(R.id.replyContentTextView);

			holder.itemLayout = itemLayout;
			holder.iconImageView = accountIconImageView;
			holder.nameTextView = nameTextView;
			holder.storyTextView = storyTextView;
			holder.timeTextView = timeTextView;
			holder.contentTextView = contentTextView;
			holder.praiseCountTextView = praiseCountTextView;
			holder.praiseIconTextView = praiseIconTextView;
			holder.replyIconTextView = replyIconTextView;
			holder.replayLayout = replayLayout;
			holder.replyNameTextView = replyNameTextView;
			holder.replyContentTextView = replyContentTextView;

			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}

		 try {
	            final BeanBbsDetail item = mArrayList.get(position);
	            String content = item.Content;
	            if (!TextUtils.isEmpty(content) && content.contains("[quote]")) {
	                String txtContent = item.Content.split("\\[\\/quote\\]")[1];
	                String txtReplContent = item.Content.split("\\[\\/quote\\]")[0];
	                if (content.contains("[/Nickname]")) {
	                    String str = item.Content.split("\\[\\/Nickname\\]")[0];
	                    String str1 = item.Content.split("\\[\\/Nickname\\]")[1];
	                    String replayNick = str.split("\\[Nickname\\]")[1];
	                    String itemContent = str1.split("\\[\\/quote\\]")[0];
	                    holder.replyNameTextView.setVisibility(View.VISIBLE);
	                    holder.replyNameTextView.setText(replayNick);
	                    holder.replyContentTextView.setText(itemContent);
	                } else {
	                    holder.replyNameTextView.setVisibility(View.GONE);
	                    holder.replyContentTextView.setText(txtReplContent.split("\\[quote]")[1]);
	                }
	                holder.replayLayout.setVisibility(View.VISIBLE);
	                holder.contentTextView.setText(txtContent);
	            } else {
	                holder.contentTextView.setText(content);
	                holder.replayLayout.setVisibility(View.GONE);
	            }
	            holder.storyTextView.setText(position + 1 + "楼");
	            holder.nameTextView.setText(item.NickName);
	            String dateString = DateUtilBase.stringFromDate(new Date(item.RecordCreateTime * 1000), DateUtilBase.DATE_ALL_ALL);
	            holder.timeTextView.setText(dateString);

	            //String imageUrl = Setting.getHeadIconUrl(item.AuthorID);
	            // 头像
//	            String path = UniversalImageLoadTool.getImageLoader().getDiskCache().get(imageUrl).getPath();
//	    		File file = new File(path);
//	    		if(file.exists()){
//	    			file.delete();
//	    		}
	        	// 头像
				LoginUtil.loadSelfUserImage(mContext,holder.iconImageView,item.AuthorID);
	            
				//UniversalImageLoadTool.disPlay(imageUrl, holder.iconImageView,R.drawable.app_ic_default_avatar);
	            
	            holder.iconImageView.setOnClickListener(new View.OnClickListener() {
	                @Override
	                public void onClick(View view) {
	            		//头像监听
	                    LoginUtil.jumpUserInfo((BaseFragmentActivity)mContext, item.AuthorID);
	                }
	            });
	            holder.praiseIconTextView.setSelected(true);
	            holder.replyIconTextView.setSelected(true);
	            
	            holder.praiseCountTextView.setText(String.valueOf(item.FavourCount)+"赞");
	            holder.praiseIconTextView.setText(item.HasFavour == 1 ?"已赞" : "点赞");
	            holder.praiseIconTextView.setOnClickListener(new ViewOnclickListener(item, holder.praiseIconTextView, holder.praiseCountTextView));
	            holder.replyIconTextView.setOnClickListener(new ViewOnclickListener(item));
	            holder.itemLayout.setOnClickListener(new ViewOnclickListener(item));
	        } catch (Exception e) {
	            e.printStackTrace();
	        }

		return convertView;
	}
	
	 class ViewOnclickListener implements View.OnClickListener{
		 public BeanBbsDetail beanBbsDetail;
		 public TextView favor;
		 public TextView favorCount;
		 private EditText editText;
		 
		 public ViewOnclickListener(){
			 
		 }
		 
		 public ViewOnclickListener(BeanBbsDetail beanBbsDetail){
			 this.beanBbsDetail = beanBbsDetail;
		 }
		 
		 public ViewOnclickListener(BeanBbsDetail beanBbsDetail, TextView favor, TextView favorCount){
			 this.beanBbsDetail = beanBbsDetail;
			 this.favor = favor;
			 this.favorCount = favorCount;
		 }
		 
		 public ViewOnclickListener(EditText editText){
				this.editText = editText;
		 }
		 
		 public void onClick(View v) {
			 switch (v.getId()) {
				
				case R.id.bbs_comment_praise_text: //点赞
					if(LoginUtil.jumpLogin((BaseFragmentActivity)mContext)){
						return;
					}
					mBeanBbsDetail = beanBbsDetail;
					mFavorTextView = favor;
					mFavorCountTextView = favorCount;
                    if(favor.getText().toString().equals("点赞")){  //点赞
                    	requestFavor();
                    }else if(favor.getText().toString().equals("已赞")){  //取消赞
                    	requestFavorCannel();
                    }
					break;
				case R.id.bbs_comment_reply_text: //回复
					if(LoginUtil.jumpLogin((BaseFragmentActivity)mContext)){
						return;
					}
					mBeanBbsDetail = beanBbsDetail;
					showPopSend(beanBbsDetail.NickName, beanBbsDetail.AuthorID);
					break;
					   //回复发送
				case R.id.send_text:
					if(LoginUtil.jumpLogin((BaseFragmentActivity)mContext)){
						return;
					}
					if(TextUtils.isEmpty(editText.getText().toString())){
						UIHelper.showToast(mContext, "请输入回复内容");
						return;
					}
					if(editText.getText().toString().length() > 1000){
						UIHelper.showToast(mContext, "请输入1000字以内回复内容");
						return;
					}
					requestReply(editText.getText().toString());
					break;
				//取消发送
				case R.id.send_cancel:
					PopUtil.getInstance().dismissPopWindow();
					break;
				//item
				case R.id.mainItemLayout:
					if(beanBbsDetail.AuthorID.equals(LoginUtil.getUserId())){
						return;
					}
					showPopSend2(beanBbsDetail);
					break;
				case R.id.mother_detail_report:
                    boolean flagLoginReport = LoginUtil.jumpLogin((BaseFragmentActivity)mContext);
					
					if(flagLoginReport){
						return;
					}
					
					Intent intent = new Intent((BaseFragmentActivity)mContext, MyReportActivity.class);
					intent.putExtra("reportType", 2);  //1 代表论坛主贴  2代表论坛评论
		            intent.putExtra("reportID", beanBbsDetail.AuthorID);
		            intent.putExtra("reportName", beanBbsDetail.NickName);
		            ((BaseFragmentActivity)mContext).startActivity(intent,true);
					
		            PopUtil.getInstance().dismissPopWindow();
					
					
					break;
				case R.id.mother_detail_cannel:
					PopUtil.getInstance().dismissPopWindow();
					
					break;
				default:
					break;
		     }
		 }
	 }
	
	//显示回复布局
	@SuppressLint("InflateParams")
	public void showPopSend(String sendToName, String replyId) {
		View view = LayoutInflater.from(mContext).inflate(R.layout.bbs_comment_send_view, null);
		TextView sendText = (TextView) view.findViewById(R.id.send_text);
		TextView cancelText = (TextView) view.findViewById(R.id.send_cancel);
		EditText sendContent = (EditText) view.findViewById(R.id.send_edit);
		//sendContent.setFilters(new InputFilter[] { new EmojiFilter() });
		sendContent.setHint("输入您回复的内容");
		sendText.setOnClickListener(new ViewOnclickListener(sendContent));
		cancelText.setOnClickListener(new ViewOnclickListener(sendContent));
		
		PopUtil.getInstance().showPopWindow((BaseFragmentActivity)mContext, null, view,Gravity.BOTTOM, null, false);
	}
	
	//举报布局
	@SuppressLint("InflateParams")
	public void showPopSend2(BeanBbsDetail beanBbsDetail) {
		View view = LayoutInflater.from(mContext).inflate(R.layout.bbs_detail_more_view, null);
		TextView repotText = (TextView) view.findViewById(R.id.mother_detail_report);
		TextView cannelText = (TextView) view.findViewById(R.id.mother_detail_cannel);
		
		cannelText.setOnClickListener(new ViewOnclickListener());
		repotText.setText("举报");
		repotText.setOnClickListener(new ViewOnclickListener(beanBbsDetail));
		
		PopUtil.getInstance().showPopWindow((BaseFragmentActivity)mContext, null, view,Gravity.BOTTOM, null, true);
	}
	
	private static class ViewHolder {
		LinearLayout itemLayout;
		CircularImageView iconImageView;
		TextView nameTextView;
		TextView timeTextView;
		TextView storyTextView;
		TextView contentTextView;
		TextView praiseCountTextView;
		TextView praiseIconTextView;
		TextView replyIconTextView;
		
		LinearLayout replayLayout;
		TextView replyNameTextView;
		TextView replyContentTextView;

	}
	
	//点赞
	public void requestFavor() {
		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();
		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);
			
			if (LoginUtil.checkIsLogin()) {
				params.put("UserID", LoginUtil.getUserId());
				params.put("LoginToken", LoginUtil.getLoginToken());
			} else {
				params.put("UserID", -1);
				params.put("LoginToken", "");
			}
			
			params.put("ThreadID", mThreadId);
			params.put("PostID", mBeanBbsDetail.PostID);

		} catch (Exception e) {
		}
		map.put("ht", params);

		ApiClient.http_post(Setting.getBbsFavorUrl(), map, null, this,REQUEST_FAVOR, true, false);
		((BaseFragmentActivity)mContext).showProgressDialog();
	}
	
	//取消赞
	public void requestFavorCannel() {
		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();
		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);
			
			if (LoginUtil.checkIsLogin()) {
				params.put("UserID", LoginUtil.getUserId());
				params.put("LoginToken", LoginUtil.getLoginToken());
			} else {
				params.put("UserID", -1);
				params.put("LoginToken", "");
			}
			
			params.put("ThreadID", mThreadId);
			params.put("PostID", mBeanBbsDetail.PostID);

		} catch (Exception e) {
		}
		map.put("ht", params);

		ApiClient.http_post(Setting.getBbsFavorCannelUrl(), map, null, this,REQUEST_FAVOR_EXIT, true,false);
		((BaseFragmentActivity)mContext).showProgressDialog();
	}
	
	//回复
	public void requestReply(String sendContent) {
		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();
		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);
			
			params.put("UserID", LoginUtil.getUserId());
			params.put("LoginToken", LoginUtil.getLoginToken());
			params.put("PostID", mBeanBbsDetail.PostID);
			params.put("Content", sendContent);
			
		} catch (Exception e) {
		}
		map.put("ht", params);

		ApiClient.http_post(Setting.getBbsCommentUrl(), map, null, this,REQUEST_REPLY, true,true);
		((BaseFragmentActivity)mContext).showProgressDialog();
	}
	
	@SuppressLint("HandlerLeak")
	public Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case MSG_FAVOR_SUCESS:  //
				String favorString = (String) msg.obj;
				try {
					JSONObject json = new JSONObject(favorString);
					
					int status = json.getJSONObject("Result").optInt("Status");
					if (status == 200) {
						mFavorTextView.setText("已赞");
					    mBeanBbsDetail.FavourCount = mBeanBbsDetail.FavourCount+1;
						mFavorCountTextView.setText(String.valueOf(mBeanBbsDetail.FavourCount)+"赞");
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}

				((BaseFragmentActivity)mContext).hideProgressDialog();
				break;

			case MSG_FAVOR_FAIL:
				((BaseFragmentActivity)mContext).hideProgressDialog();
				break;
			case MSG_FAVOR_EXIT_SUCESS:
				String favorCannelString = (String) msg.obj;
				try {
					JSONObject json = new JSONObject(favorCannelString);
					
					int status = json.getJSONObject("Result").optInt("Status");
					if (status == 200) {
						mFavorTextView.setText("点赞");
					    mBeanBbsDetail.FavourCount = mBeanBbsDetail.FavourCount-1;
						mFavorCountTextView.setText(String.valueOf(mBeanBbsDetail.FavourCount)+"赞");
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}

				((BaseFragmentActivity)mContext).hideProgressDialog();
				break;

			case MSG_FAVOR_EXIT_FAIL:
				((BaseFragmentActivity)mContext).hideProgressDialog();
				break;
			case MSG_REPLY_SUCESS:
				String replyString = (String) msg.obj;
				try {
					JSONObject json = new JSONObject(replyString);
					
					int status = json.getJSONObject("Result").optInt("Status");
					if (status == 200) {
						PopUtil.getInstance().dismissPopWindow();
						//刷新
						BbsDetailActivity.getInstance().request(false);
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}

				((BaseFragmentActivity)mContext).hideProgressDialog();
				break;
			case MSG_REPLY_FAIL:
				break;
			default:
				break;
			}
		};
	};

	@Override
	public void RequestComplete(Object object, Object data) {
		if(object.equals(REQUEST_FAVOR)){
			Message msg = mHandler.obtainMessage();
			msg.what = MSG_FAVOR_SUCESS;
			msg.obj = (String) data;
			mHandler.sendMessage(msg);
		}
		else if(object.equals(REQUEST_FAVOR_EXIT)){
			Message msg = mHandler.obtainMessage();
			msg.what = MSG_FAVOR_EXIT_SUCESS;
			msg.obj = (String) data;
			mHandler.sendMessage(msg);
		}
		else if(object.equals(REQUEST_REPLY)){
			Message msg = mHandler.obtainMessage();
			msg.what = MSG_REPLY_SUCESS;
			msg.obj = (String) data;
			mHandler.sendMessage(msg);
		}
	}

	@Override
	public void RequestError(Object object, int arg1, String arg2) {
		if(object.equals(REQUEST_FAVOR)){
			Message msg = mHandler.obtainMessage();
			msg.what = MSG_FAVOR_FAIL;
			mHandler.sendMessage(msg);
		}else if(object.equals(REQUEST_FAVOR_EXIT)){
			Message msg = mHandler.obtainMessage();
			msg.what = MSG_FAVOR_EXIT_FAIL;
			mHandler.sendMessage(msg);
		}else if(object.equals(REQUEST_REPLY)){
			Message msg = mHandler.obtainMessage();
			msg.what = MSG_REPLY_FAIL;
			mHandler.sendMessage(msg);
		}
		
	}

}
